package com.guqinghan.guqinghan_03_sqllite;

import androidx.appcompat.app.AppCompatActivity;

import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.os.Bundle;
import android.view.View;

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
    }

    /*生成db文件*/
    public void createDB(View view) {
        System.out.println("生成db文件");
        SQLiteOpenHelper sqLiteOpenHelper = MyOpenSqlLite.getInstance(this);
        // database文件夹的创建需要下边这句话
        SQLiteDatabase readableDatabase = sqLiteOpenHelper.getReadableDatabase();
        if (readableDatabase!=null){
            System.out.println("创建成功");
        }else {
            System.out.println("创建失败");
        }
    }

    /*查询操作*/
    public void query(View view) {
        System.out.println("开始查询");
        SQLiteOpenHelper sqLiteOpenHelper = MyOpenSqlLite.getInstance(this);
        // database文件夹的创建需要下边这句话
        SQLiteDatabase readableDatabase = sqLiteOpenHelper.getReadableDatabase();
        if (readableDatabase.isOpen()) {
            //查询
            Cursor cursor = readableDatabase.rawQuery("select * from person", null);
            while (cursor.moveToNext()) {
                int id = cursor.getColumnIndex("_id");
                int _id = cursor.getInt(id);
                int name1 = cursor.getColumnIndex("name");
                String name = cursor.getString(name1);
                System.out.println("id  == "+_id +"姓    名 == "+ name);
                System.out.println("结束查询");
            }
            // 一定要关闭游标
            cursor.close();
            readableDatabase.close();
        }

    }

    /*插入操作*/
    public void insert(View view) {
        System.out.println("开始插入");
        SQLiteOpenHelper sqLiteOpenHelper = MyOpenSqlLite.getInstance(this);
        // database文件夹的创建需要下边这句话
        SQLiteDatabase writableDatabase = sqLiteOpenHelper.getWritableDatabase();
        // 必须要先确定数据库是否打开
        if (writableDatabase.isOpen()){
            String sql = "insert into person(name) values('白痴')";
            writableDatabase.execSQL(sql);
        }
        writableDatabase.close();
    }

}
